package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.domain.Setmeal;
import com.itheima.reggie.domain.SetmealDish;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealDishService setmealDishService;

    /****
     * 套餐分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<SetmealDto>> page(int page, int pageSize, String name) {
        //1.分页条件构造
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();
        //2.设置查询条件
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper();
        lqw.like(name != null, Setmeal::getName, name);
        lqw.orderByDesc(Setmeal::getUpdateTime);
        //3.查询
        setmealService.page(setmealPage, lqw);
        //4.拷贝
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");
        //5.给SetmealDto设置套餐分类名字
        List<Setmeal> records = setmealPage.getRecords();
        List<SetmealDto> list = new ArrayList<>();
        for (Setmeal setmeal : records) {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(setmeal, setmealDto);
            Category category = categoryService.getById(setmeal.getCategoryId());
            setmealDto.setCategoryName(category.getName());
            list.add(setmealDto);
        }
        setmealDtoPage.setRecords(list);
        return R.success(setmealDtoPage);
    }

    /****
     * 套餐修改回显数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getSetmeal(@PathVariable Long id) {
        //①.创建setmealDto
        SetmealDto setmealDto = new SetmealDto();
        //②.查询
        Setmeal setmeal = setmealService.getById(id);
        //③.拷贝
        BeanUtils.copyProperties(setmeal, setmealDto);
        //4.查询套餐菜品
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> list = setmealDishService.list(lqw);
        //5.查询菜品的分类名
        Category category = categoryService.getById(setmeal.getCategoryId());
        //6.设置套餐菜品和菜品分类名
        setmealDto.setSetmealDishes(list);
        setmealDto.setCategoryName(category.getName());

        //7.返回结果
        return R.success(setmealDto);
    }

    /***
     * 套餐修改
     * @param setmealDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto) {
        log.info("修改的套餐信息:{}", setmealDto.toString());
        setmealService.updateWithSetmealDish(setmealDto);
        return R.success("套餐修改成功!");
    }

    /***
     * 套餐添加
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        setmealService.saveWithSetmealDish(setmealDto);
        return R.success("保存成功");
    }

    /*****
     * 启售状态修改
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable int status, Long[] ids) {
        for (Long id : ids) {
            Setmeal setmeal = new Setmeal();
            setmeal.setStatus(status);
            setmeal.setId(id);
            setmealService.updateById(setmeal);
        }
        return R.success("启售状态修改成功!");
    }

    /****
     * 删除套餐
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids) {
        setmealService.deleteByIds(ids);
        return R.success("删除成功");
    }

    /***
     * 套餐查询
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R<List<SetmealDto>> getSetmeal(Setmeal setmeal) {
        //1.条件构造器
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        setmealLambdaQueryWrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        //2.查询套餐
        List<Setmeal> setmealList = setmealService.list(setmealLambdaQueryWrapper);
        //3.查询套餐对应的菜品
        List<SetmealDto> setmealDtos = setmealList.stream().map(item -> {
            SetmealDto setmealDto = new SetmealDto();
            //拷贝
            BeanUtils.copyProperties(item, setmealDto);
            //根据套餐id查询对应的菜品信息
            LambdaQueryWrapper<SetmealDish> setmealDishlqw = new LambdaQueryWrapper<>();
            setmealDishlqw.eq(item.getId() != null, SetmealDish::getSetmealId, item.getId());

            List<SetmealDish> setmealDishList = setmealDishService.list(setmealDishlqw);
            setmealDto.setSetmealDishes(setmealDishList);
            return setmealDto;
        }).collect(Collectors.toList());
        return R.success(setmealDtos);
    }

     @GetMapping("/dish/{id}")
    public R<List<DishDto>> getDish(@PathVariable Long id){
        log.info("查询的套餐:{}" ,id);
         //1.查询套餐对应的菜品id
         LambdaQueryWrapper<SetmealDish> setmealDishLqw = new LambdaQueryWrapper<>();
         setmealDishLqw.eq(id != null,SetmealDish::getSetmealId,id);
         List<SetmealDish> setmealDishList = setmealDishService.list(setmealDishLqw);
         List<Long> dishIds = setmealDishList.stream().map(setmealDish -> {
             Long dishId = setmealDish.getDishId();
             return dishId;
         }).collect(Collectors.toList());
         //2.获取菜品
         List<Dish> dishList = dishService.listByIds(dishIds);
         List<DishDto> dishDtoList = dishList.stream().map(dish -> {
             DishDto dishDto = new DishDto();
             BeanUtils.copyProperties(dish, dishDto);
             return dishDto;
         }).collect(Collectors.toList());
         //3.填充份数属性
         for (SetmealDish setmealDish : setmealDishList) {
             for (DishDto dishDto : dishDtoList) {
                 dishDto.setCopies(setmealDish.getCopies());
             }
         }
         return R.success(dishDtoList);
     }
}
